/* eslint-disable no-undef */
<!--
 * @author liganghao
 -->
<template>
  <el-container id="roleuserallot">
    <split-pane split="vertical" :min-percent="0" :default-percent="28">
      <template slot="paneL">
        <div class="leftWrap">
          <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
            <el-tab-pane
              v-for="(item,i) in tabList"
              :key="i"
              :label="item.dictName"
              :name="item.dictValue"
            >
              <div class="roleList">
                <!--<el-row v-if="i == 1">
                  <el-col :span="20">
                    <el-cascader
                      ref="refHandle"
                      v-model="roleValue"
                      :props="defaultProps"
                      :options="orgTreeData"
                      clearable
                    />
                  </el-col>
                  <el-col :span="3">
                    <el-button style="padding: 10px;" type="primary" @click="searchRole">搜索</el-button>
                  </el-col>
                </el-row>-->
                <div
                  v-for="(ite,n) in roleList"
                  :key="n"
                  :class="{ 'active': ite.id == roleId }"
                  class="roleitem"
                  @click="getRoleInfo(ite.id,ite)"
                >
                  <p class="rolename">
                    <span>{{ ite.roleName }}</span>
                    <span>{{ ite.userCount }}人</span>
                  </p>
                  <span class="playbtn">
                    <i class="el-icon-d-arrow-right" />
                  </span>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template slot="paneR">
        <el-main class="roleuserallot-main">
          <el-row><!--
        <el-col :span="16">
          <span style="line-height:46px">当前角色所属组织：{{ orgNameAll || '系统角色' }}</span>
        </el-col>-->
            <el-col :span="24">
              <div class="btns" style="text-align:right;">
                <el-button
                  v-permission="'roleuserallotInsert'"
                  style="margin-bottom: 10px;"
                  @click="addUser"
                >添加用户
                </el-button>
                <el-button
                  v-permission="'roleuserallotDelete'"
                  style="margin-bottom: 10px;"
                  @click="handleDeletes"
                >批量删除
                </el-button>
              </div>
            </el-col>
          </el-row>

          <el-table
            ref="rolemantable"
            v-loading="listLoading"
            :header-cell-style="rowClass"
            :data="list"
            class="tableScope"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <!--<el-table-column prop="userName" label="用户名称" show-overflow-tooltip width="200" />-->
            <el-table-column prop="userRealname" label="真实姓名" show-overflow-tooltip />
            <el-table-column prop="jieMphoneNumber" label="手机号码" show-overflow-tooltip />
            <el-table-column prop="orgAllName" label="所属组织" show-overflow-tooltip />
            <el-table-column
              label="操作"
              fixed="right"
              align="center"
              width="150"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  v-permission="'roleuserallotDelete'"
                  type="text"
                  size="mini"
                  @click="handleDelete(scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="btn-pagion fix">
            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="listQuery.page"
              :limit.sync="listQuery.limit"
              @pagination="getList"
            />
          </div>
        </el-main>
      </template>
    </split-pane>
    <el-dialog
      v-el-drag-dialog
      :title="'添加用户'"
      :visible.sync="dialogFormVisible"
      center
      fullscreen
      :close-on-click-modal="false"
    >
      <add-user
        ref="resetAll"
        v-loading.fullscreen.lock="fullscreenLoading"
        :before-list="beforeList"
        @userData="userData"
      />
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="dialogFormVisible = false">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="insertUser()">确定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>
<script>
import {
  roleList,
  queryMenu,
  userList,
  deleteUser,
  insertRoleUser,
  getDictByCode,
  getComLeaf
} from '@/views/roleuserallot/api/index'
import waves from '@/directive/waves' // Waves directive
import CryptoJS from '@/utils/aesJiaJM'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import addUser from '@/views/roleuserallot/components/adduser' // Secondary package based on el-pagination
import permission from '@/directive/permission/index.js' // 权限判断指令
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import splitPane from 'vue-splitpane'

export default {
  name: 'Roleuserallot',
  components: { Pagination, addUser, splitPane },
  directives: { permission, waves, elDragDialog },
  data() {
    return {
      activeName: 'JSLX01',
      rolwloading: false,
      fullscreenLoading: false,
      roleList: [],
      total: 0,
      dialogTotal: 0,
      dialogFormVisible: false,
      listQuery: {
        page: 1,
        limit: 10
      },
      beforeList: [],
      list: [],
      listLoading: false,
      menuLoading: false,
      treeData: [],
      multipleSelection: [],
      dialogMultipleSelection: [],
      checkedData: [], // 选中的节点
      showOrg: '',
      orgNameAll: '',
      roleId: '',
      ptObj: {},
      qyObj: {},
      tabList: [],
      tabValue: '', // tab默认选中
      qyDialogVisible: false,
      curNodeOrgIdOrDeptId: {
        orgId: '',
        deptId: ''
      },
      orgTreeId: '',
      roleValue: [],
      defaultProps: {
        lazy: true,
        children: 'list',
        label: 'orgName',
        value: 'id',
        checkStrictly: true,
        lazyLoad(node, resolve) {
          return new Promise((res, reject) => {
            getComLeaf({ parentId: node.data.id }).then(response => {
              resolve(response.data.data)
            }).catch(error => {
              reject(error)
            })
          })
        }
      },
      orgTreeData: []
    }
  },
  watch: {
    roleValue(val) {
      this.$refs.refHandle[0].toggleDropDownVisible()// 监听值发生变化就关闭它
      if (val.length === 0) {
        this.orgTreeId = ''
        this.$refs.refHandle[0].toggleDropDownVisible()// 监听值发生变化就关闭它
        this.getRoleList()
      }
    }
  },
  created() {
    // this.getTreeData()
    this.getTabList()
  },
  methods: {
    /*
      * 获取组织树
      * */
    getTreeData() {
      this.treeLoading = true
      return new Promise((resolve, reject) => {
        getComLeaf().then(response => {
          this.orgTreeData = response.data.data
        }).catch(error => {
          reject(error)
        })
      })
    },
    /*
      * 角色查询
      * */
    searchRole() {
      this.orgTreeId = this.roleValue[this.roleValue.length - 1]
      this.getRoleList()
    },
    getRoleList() {
      this.rolwloading = true
      return new Promise((resolve, reject) => {
        roleList({
          orgId: this.orgTreeId,
          roleType: this.tabValue,
          viewFlag: this.$route.fullPath === '/sys/roleuserallot' ? '' : 1
        }).then(response => {
          this.rolwloading = false
          if (response.data.data) {
            this.roleList = response.data.data.rows
            this.$nextTick(() => {
              if (!this.roleId) {
                this.roleId = this.roleList[0].id
              }
              this.getList()
            })
          }
        }).catch(error => {
          this.rolwloading = false
          reject(error)
        })
      })
    },
    getTabList() {
      this.rolwloading = true
      return new Promise((resolve, reject) => {
        getDictByCode('JSLX').then(response => {
          this.rolwloading = false
          if (response.data.data) {
            this.tabList = (response.data.data && response.data.data.length > 0) ? response.data.data[0].list : []
            this.tabValue = this.tabList[0].dictValue
            this.$nextTick(() => {
              this.getRoleList()
            })
          }
        }).catch(error => {
          this.rolwloading = false
          reject(error)
        })
      })
    },
    // 获取所有数据
    getAllList() {
      this.listLoading = true
      const cobj = {
        adminFlag: 'YHBS02'
      }
      const query = {
        ...cobj,
        page: 1,
        pageSize: this.total,
        id: this.roleId
      }
      return new Promise((resolve, reject) => {
        userList(query).then(response => {
          this.beforeList = response.data.data.rows
          this.list.forEach(element => {
            if (element.phoneNumber) {
              element.jieMphoneNumber = CryptoJS.$aesJieM(element.phoneNumber)
            }
          })
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    },
    // 获取列表数据
    getList(obj) {
      this.listLoading = true
      const cobj = {
        adminFlag: 'YHBS02'
      }
      const query = {
        ...cobj,
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        id: this.roleId
      }
      return new Promise((resolve, reject) => {
        userList(query).then(response => {
          this.list = response.data.data.rows
          this.list.forEach(element => {
            if (element.phoneNumber) {
              element.jieMphoneNumber = CryptoJS.$aesJieM(element.phoneNumber)
            }
          })
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    },

    rowClass({ row, rowIndex }) {
      return {
        padding: '5px 0',
        height: '20px',
        background: 'rgba(247,247,248,1)'
      }
    },
    /*
        params: 无
        return:无
        function:获取权限树结构
      */
    getMenu() {
      this.menuLoading = true
      return new Promise((resolve, reject) => {
        queryMenu().then(response => {
          this.menuLoading = false
          this.treeData = response.data.data
        }).catch(error => {
          reject(error)
          this.menuLoading = false
        })
      })
    },
    /*
        params:原始数据
        return:无
        function：设置禁用
      */
    setNoCheck(data) {
      var vueObj = this
      if (data.length > 0) {
        data.forEach((item, i) => {
          item.disabled = true
          if (item.list && item.list.length > 0) {
            vueObj.setNoCheck(item.list)
          }
        })
      }
      return data
    },
    /**
			 * tab选中
			 */
    handleClick(tab, event) {
      this.orgTreeId = ''
      this.roleValue = []
      if (this.tabValue !== tab.name) {
        this.tabValue = tab.name
        this.getRoleList()
      } else {
        this.tabValue = tab.name
      }
    },
    getRoleInfo(id, data) {
      // this.setCheckedKeys(data)
      console.log(data)
      this.showOrg = data.orgName
      this.orgNameAll = data.orgNameAll
      this.roleId = id
      this.getRoleList()
    },
    /*
        params:点角色对应的code对应权限
        return:无
        params:设置树的选中与否
      */
    setTree(code) {
      var arr = code.split(',') || []
      this.checkedData = arr
    },
    /*
        params:点角色对应的code对应权限
        return:无
        params:设置树的选中与否
      */
    setCheckedKeys(code) {
      var tmp = code
      if (tmp.charAt(tmp.length - 1) === ',') {
        tmp = tmp.slice(0, tmp.length - 1)
      }
      var arr = tmp.split(',') || []
      this.$refs.tree.setCheckedKeys(arr)
    },
    handleDeletes() {
      const arr = []
      if (this.multipleSelection.length > 0) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.listLoading = true
          this.multipleSelection.forEach(item => {
            arr.push(item.id)
          })
          const ids = arr.join(',')
          this.deleteUser(ids)
        }).catch(() => {
        })
      } else {
        this.$message({
          message: '请选择需要删除的数据！',
          type: 'warning'
        })
      }
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteUser(row.id)
      }).catch(() => {
      })
    },
    deleteUser(ids) {
      return new Promise((resolve, reject) => {
        deleteUser(ids, this.roleId).then((res) => {
          this.listLoading = false
          this.$message({
            message: '删除成功！',
            type: 'success'
          })
          this.getRoleList()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 添加用户
    addUser() {
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.resetAll.emptySelect()
        this.$refs.resetAll.resettingall()
      })
    },
    handleSelectionChange(arr) {
      this.multipleSelection = arr
    },
    getRowKeys(row) {
      return row.id
    },
    userData(val) {
      this.dialogMultipleSelection = val
    },
    insertUser() {
      if (this.dialogMultipleSelection.length > 0) {
        var arr = []
        this.dialogMultipleSelection.forEach(item => {
          arr.push(item.id)
        })
        var ids = arr.join(',')
        this.fullscreenLoading = true
        this.dialogListLoading = true
        return new Promise((resolve, reject) => {
          insertRoleUser(this.roleId, ids).then(() => {
            this.dialogListLoading = false
            this.dialogFormVisible = false
            this.$message({
              message: '添加用户成功！',
              type: 'success'
            })
            this.fullscreenLoading = false
            this.getRoleList()
          }).catch(error => {
            reject(error)
          })
        })
      } else {
        this.$message({
          message: '请选择用户！',
          type: 'warning'
        })
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" type="text/scss">

  #roleuserallot {
    height: calc(100vh - 64px);
    padding: 10px;
    overflow: hidden;
    .vue-splitter-container {
      width: 100%;
      overflow: hidden;
    }
    .leftWrap {
      height: 100%;
      background: #fff;
      overflow-y: auto;
      .roleList {
        font-size: 14px;
        .roleitem {
          padding-left: 15px;
          height: 40px;
          line-height: 40px;
          background: #fff;
          margin-bottom: 5px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          cursor: pointer;
          &.active {
            background-color: #e5e5e5;
            .playbtn {
              display: inline-block;
            }
          }
          &.roleheader {
            background: #f7f7f8;
          }
          &:hover {
            .playbtn {
              display: inline-block;
            }
          }
          span {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .rolename {
            display: inline-block;
            width: 90%;
            span:nth-child(2) {
              padding: 3px 4px;
              @include font-color($mainColor);
              border-radius: 5px;
            }
          }
          .rolepower {
            display: inline-block;
            width: 245px;
            text-align: right;
          }
          .playbtn {
            display: none;
            cursor: pointer;
            width: 20px;
          }
        }
      }
    }
    .el-main {
      padding: 0 0 0 10px;
    }
    .roleuserallot-main {
      height: 100%;
      background-color: #fff;
      overflow-y: auto;
      .el-tabs {
        height: 100%;
        .el-tabs__content {
          height: calc(100% - 40px);
          overflow-y: auto;
          &::-webkit-scrollbar {
            display: none;
          }
        }
        .btns {
          text-align: right;
        }
      }
      &::-webkit-scrollbar {
        display: none;
      }
    }

    .roleList,
    .leftWrap {
      &::-webkit-scrollbar {
        display: none;
      }
      .dialog-footer {
        text-align: center;
        padding-bottom: 20px;
      }
    }

    @keyframes antStatusProcessing {
      0% {
        transform: scale(0.8);
        opacity: 0.5;
      }
      to {
        transform: scale(2.4);
        opacity: 0;
      }
    }
  }
</style>
